<template>
  <div class="yzh-basic">
    <div class="flex justify-between pb-5">
      <TitleName
        title="出库记录"
        icon="i-carbon-bookmark-filled"
        class="title"
      ></TitleName
      ><!-- 
        :iconStyle="{ color: '#000' }" -->
      <el-row class="w-8/12 text-right" :gutter="20" justify="end">
        <el-col :span="5">
          <el-button class="w-full" type="primary" plain @click="handleAdd"
            >新增</el-button
          >
        </el-col>
      </el-row>
    </div>

    <el-table
      v-loading="loading"
      :data="listData"
      row-key="id"
      stripe
      border
      ref="refTable"
    >
      <!-- @row-click="clickRow" -->
      <el-table-column type="expand" width="60">
        <template #default="props">
          <div>
            <el-table :data="props.row.productList" stripe>
              <el-table-column
                prop="invoiceName"
                label="产品名称"
                min-width="200"
              >
              </el-table-column>
              <el-table-column prop="number" label="产品编号" min-width="150">
              </el-table-column>
              <!-- <el-table-column prop="price" label="标准单价(元)" width="100">
              </el-table-column> -->
              <el-table-column
                prop="actualPrice"
                label="实际售价(元)"
                width="100"
              >
              </el-table-column>
              <el-table-column prop="invoiceNum" label="数量" width="50">
              </el-table-column>
              <!-- <el-table-column prop="discount" label="折扣(%)" width="80">
      </el-table-column> -->
              <el-table-column
                prop="invoiceTotalPrice"
                label="开票总金额"
                width="100"
              >
              </el-table-column>
              <el-table-column prop="unit" label="产品规格" width="80">
                <template #default="scope">
                  <dict-drop
                    :options="measurement_unit"
                    :value="scope.row.unit"
                    :isDrop="false"
                /></template>
              </el-table-column>
              <el-table-column
                prop="invoiceSpecification"
                label="规格型号"
                width="100"
              >
              </el-table-column>
              <!-- <el-table-column
                prop="serviceDateArr"
                label="服务时间"
                width="230"
              >
                <template #default="scope">
                  <div>
                    <div v-if="scope.row.$cellEdit">
                      <el-date-picker
                        :clearable="true"
                        style="width: 100%"
                        v-model="scope.row.serviceDateArr"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                      />
                    </div>
                    <div v-else>
                      {{ strToArr(scope.row.serviceDateArr).toString() }}
                    </div>
                  </div>
                </template>
              </el-table-column> -->
              <!-- <el-table-column prop="present" label="赠品" width="150">
              </el-table-column>
              <el-table-column prop="remark" label="备注" width="150">
              </el-table-column>
              <el-table-column prop="extensionNo" label="分机号" width="100">
              </el-table-column> -->
            </el-table>
          </div></template
        >
      </el-table-column>
      <el-table-column prop="createName" label="创建人员" width="100">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="warehouseMsg"
        label="出库同步消息"
        min-width="180"
        align="center"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        width="180"
        class-name="small-padding"
      >
        <template #default="scope">
          <el-button
            icon="SuccessFilled"
            type="primary"
            plain
            size="small"
            @click="rowDel(scope.row)"
          >
            <div>删除</div>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="dialogParam.title"
      v-model="dialogParam.open"
      :width="dialogParam.width"
      @close="cancelFn"
    >
      <el-form
        ref="form"
        :model="formData"
        :rules="formRules"
        label-width="110px"
        :disabled="formDisabled"
      >
        <el-row>
          <el-col :span="24">
            <avue-crud
              ref="crudProduct"
              :option="crudOptionProduct"
              :data="formData.productInfoList"
              class="hide-required-asterisk"
              :row-class-name="rowClassName"
            >
              <template #menu="{ row }">
                <el-switch
                  v-model="row.openInvoice"
                  @change="changeSwitch(row)"
                />
                <!-- <el-button
                  plain
                  icon="Delete"
                  link
                  @click="delRowProduct(row, index)"
                  >删除</el-button
                > -->
              </template>
              <template #empty>
                <div>暂无数据</div>
              </template>
            </avue-crud>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div>
          <slot name="bottomBtn"></slot>
          <!-- <el-button @click="cancelUpload">取消</el-button> -->
          <el-button type="primary" @click="saveInvoice">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="OrderOutbound">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useCommonStore from '@/store/modules/common'
import { validatePhoneNot, maxDecimals } from '@/utils/validate'
import {
  crudOption,
  measurement_unit //产品单位
} from '@/hooks/dict/order'
import {
  listOutbound,
  updateOutbound,
  getSalesOrder
} from '@/api/indentManage/indent'
import { delInvoice } from '@/api/invoiceManage/invoice'
import { strToArr, myToFixed } from '@/utils/commo'

const router = useRouter()
const route = useRoute()
const props = defineProps({
  orderId: {
    type: [Number, String],
    require: true
  },
  tableParam: {
    type: Object,
    require: false
  }
})
const { proxy } = getCurrentInstance()
const commonStore = useCommonStore()
const companyData = ref([])
commonStore.getCompanyData().then(e => {
  companyData.value = e
})
const data = reactive({
  listData: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10
  }
})
let { listData, queryParams } = toRefs(data)

const dialogParam = ref({
  open: false,
  title: '出库信息',
  width: '1100px'
})
const crudOptionProduct = ref({
  ...crudOption,
  menu: true,
  menuTitle: '是否出库',
  header: false,
  column: [
    {
      label: '开票名称',
      prop: 'invoiceName',
      cell: false,
      minWidth: '150',
      rules: [
        {
          required: true,
          message: '请输入开票名称',
          trigger: 'blur'
        }
      ]
    },
    {
      label: '开票规格型号',
      width: '150',
      prop: 'invoiceSpecification',
      cell: false
    },
    {
      label: '单位',
      prop: 'unit',
      type: 'select',
      width: '90',
      clearable: false,
      dicData: measurement_unit,
      cell: false
    },
    {
      label: '实际售价',
      prop: 'actualPrice',
      type: 'number',
      min: 0,
      class: 'w-full',
      width: '80',
      controls: false,
      cell: false
    },
    // {
    //   label: '数量(已开)',
    //   prop: 'openedNum',
    //   type: 'number',
    //   // min: 0, //由于是红蓝单所以可负数
    //   class: 'w-full',
    //   controls: false,
    //   // precision: 0,
    //   width: '100',
    //   cell: false
    // },
    {
      label: '数量',
      prop: 'invoiceNum',
      type: 'input',
      // min: 0, //由于是红蓝单所以可负数
      class: 'w-full',
      controls: false,
      // precision: 0,
      width: '100',
      rules: [
        {
          required: true,
          message: '请输入数量',
          trigger: 'blur'
        },
        {
          validator: (rule, value, callback) => {
            maxDecimals(rule, value, callback, 6)
          }
        }
      ],
      blur: val => {
        const { value, row } = val
        if (0 < value && value <= row.num - row.openedNum) {
          row.unOpenedPrice = myToFixed(row.actualPrice * row.invoiceNum, 6)
        } else {
          proxy.$message.error('数量不能小于0或大于剩余数量')
          row.invoiceNum = ''
        }
      },
      cell: true
    },
    {
      label: '剩余数量',
      prop: 'surplusNum',
      type: 'number',
      // min: 0, //由于是红蓝单所以可负数
      class: 'w-full',
      controls: false,
      // precision: 0,
      width: '80',
      cell: false
    },
    // {
    //   label: '总数量',
    //   prop: 'num',
    //   type: 'number',
    //   // min: 0, //由于是红蓝单所以可负数
    //   class: 'w-full',
    //   controls: false,
    //   // precision: 0,
    //   width: '80',
    //   cell: false
    // },
    // {
    //   label: '金额(已开)',
    //   prop: 'openedPrice',
    //   type: 'number',
    //   min: 0,
    //   class: 'w-full',
    //   width: '100',
    //   controls: false,
    //   cell: false
    // },
    // {
    //   label: '金额',
    //   prop: 'unOpenedPrice',
    //   type: 'number',
    //   min: 0,
    //   class: 'w-full',
    //   width: '100',
    //   controls: false,
    //   cell: false
    // },
    {
      label: '总价(元)',
      width: '100',
      prop: 'totalPrice',
      cell: false
    },
    {
      label: '税率',
      width: '100',
      prop: 'taxRate',
      cell: false
    }
  ]
})
const formData = ref({})
const formRules = ref({})

watchEffect(() => {
  if (props.orderId) {
    getList()
  }
})

function getList() {
  // let query = {
  //   ...queryParams.value,
  //   orderId: props.orderId
  // }
  listOutbound(props.orderId).then(async res => {
    let resData = {}
    resData = res.data
    listData.value = resData.map(item => {
      return { ...item }
    })
  })
}
const changeSwitch = row => {
  row.$cellEdit = row.openInvoice
  if (row.openInvoice && row.invoiceNum && row.invoiceNum == 0) {
    row.invoiceNum = ''
  }
}
const rowClassName = ({ row, rowIndex }) => {
  // console.log('row,rowIndex==>', row, rowIndex)
  return row.openInvoice ? '' : 'unInvoice'
}
// 新增
const handleAdd = async () => {
  let res = await getSalesOrder(props.orderId)
  if (res.code !== 200) return
  dialogParam.value.open = true
  formData.value = {
    ...res.data,
    productInfoList: res.data.productInfoList.map(item => {
      return {
        ...item,
        surplusNum: item.invoiceNum,
        openInvoice: item.invoiceNum && item.invoiceNum != 0,
        $cellEdit: item.invoiceNum && item.invoiceNum != 0
      }
    })
  }
}
// 确定新增
const saveInvoice = () => {
  updateOutbound(formData.value).then(res => {
    if (res.code == 200) {
      dialogParam.value.open = false
      getList()
    }
  })
}
// 删除
function rowDel(row) {
  proxy.$modal
    .confirm('是否删除该票据')
    .then(function () {
      let data = {
        ids: [row.id],
        type: 'warehouse'
      }
      return delInvoice(data)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
// 保存行
const rowSave = row => {
  row.$cellEdit = false
  updateOutbound(row).then(res => {
    if (res.code == 200) {
      // console.log('res.code===>', res)
      getList()
    }
  })
  // console.log('保存行===>', row)
}
</script>
<style lang="scss" scoped>
.title {
  font-size: 16px;
  font-weight: 600;
}

:deep(.hide-required-asterisk) {
  .avue-crud__body {
    .el-card__body {
      padding: 15px 0 !important;
    }
  }
}
.hide-required-asterisk {
  :deep(.unInvoice) {
    @apply bg-slate-200;
  }
}
</style>
